const {Produces,Op} = require('../Model')

let fn_data= async (ctx,next)=>{
console.log(11);
let keyword = ctx.request.query.keyword;
console.log(keyword);
    if(keyword!='undefined'){
        ctx.body = await Produces.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword)?-1:parseInt(keyword)},
                    {name:keyword},
                    {price:isNaN(keyword)?-1:parseFloat(keyword)},
                    {stock:isNaN(keyword)?-1:parseInt(keyword)}
                ]
            }
        })
    }else{
        ctx.body = await Produces.findAll()
    }
}


let fn_del = async (ctx,next)=>{
    let id = ctx.request.params.id;
    console.log(id);
    // ctx.body = await Produces.findByPk(id)
     await Produces.destroy({where:{
        id:id
    }})
    ctx.body = await Produces.findAll()
}


let fn_endit = async (ctx,next)=>{
    let id = ctx.request.params.id;
    console.log(id);
     ctx.body = await Produces.findByPk(id)
}

let fn_addorendit= async (ctx,next)=>{
    let obj = ctx.request.body;
    console.log(obj);
    if(obj.id){
        await Produces.update({name:obj.name,price:parseFloat(obj.price),stock:parseInt(obj.stock)},{where:{id:obj.id}})
        ctx.body = {
            code:1000,
            msg:"编辑成功"
        }
    }else{
        await Produces.create({name:obj.name,price:parseFloat(obj.price),stock:parseInt(obj.stock)})
        ctx.body = {
            code:1000,
            msg:"添加成功"
        }
    }
}

module.exports = {
    'get /produce':fn_data,
    'delete /produce/:id':fn_del,
    'get /produce/:id':fn_endit,
    'put /produce':fn_addorendit,
    'post /produce':fn_addorendit
}